from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse, StreamingHttpResponse
from django.template import loader
import csv

'''
小的csv
'''

def index(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = "attachment;filename='abc.csv" # 设置标题 attachment代表以附件形式下载
    # with open('xx.csv','w') as fp:
    #     csv.writer(fp)
    writer = csv.writer(response)
    writer.writerow(['username','age'])
    writer.writerow(['zhiliao','10'])
    return response

def template_csv_view(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = "attachment;filename=abc.csv" # 设置标题 attachment代表以附件形式下载
    context = {         # 内容
        'rows':[
            ['username','age'],
            ['zhiliao','10'],
        ]
    }
    template = loader.get_template(     # 设置模板
        "my_template.html"
    )
    csv_template = template.render(context) # 传入
    response.content = csv_template
    return response

'''
大的csv
'''
# class Echo:
#     def write(self,value):
#         return value

def large_csv_view(request):
    response = StreamingHttpResponse(content_type='text/csv')
    response['Content-Disposition'] = "attachment;filename=large.csv"
    # response.streaming_content = ('username,age\n','zhiliao,10\n')
    rows = ("Row {},{}\n".format(row,row) for row in range(0,1000000))
    response.streaming_content = rows
    return response